package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取相应
        ServerHttpResponse response = exchange.getResponse();
        //判断当前对象是否未登录对象,如果是,则放行
        if (request.getURI().getPath().contains("/admin/login")){
            //放行
            return chain.filter(exchange);
        }
        //获取当前请求头信息
        HttpHeaders headers = request.getHeaders();
        //获取jwt金牌信息
        String jetToKen = headers.getFirst("token");
        //判断当前临牌是否存在,
        if (StringUtils.isEmpty(jetToKen)){
            //如果不存在,则向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //过滤器拒绝访问
            return response.setComplete();
        }
        //如果临牌存在,解析jwt临牌,判断该临牌是否合法,
        try {
            JwtUtil.parseJWT(jetToKen);
        }catch (Exception e){
            e.printStackTrace();
            //如果临牌不合法,则向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //如果临牌合法,则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
